import { useEffect, useRef, useState } from 'react';

export default function App() {
  const [todoText, setTodoText] = useState('');
  const [todoData, setTodoData] = useState([]);
  const titleRef = useRef(null);

  //视图渲染后去更改DOM节点里的文本节点
  useEffect(() => {
    setTimeout(() => {
      titleRef.current.innerText = '待办事项列表';
    }, 1000);
  }, []);

  const addTodo = () => {
    if (!todoText.length) return;
    setTodoData([
      ...todoData,
      {
        id: new Date().getTime(),
        content: todoText,
        completed: false
      }
    ]);
    setTodoText('');
  };

  const toggleTodo = (id) => {
    setTodoData(
      todoData.map((todo) => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      })
    );
  };

  const removeTodo = (id) => {
    setTodoData(todoData.filter((todo) => todo.id !== id));
  };

  return (
    <div>
      <div>
        <h1 ref={titleRef}>TodoList</h1>
        <input
          type="text"
          placeholder="Input some..."
          value={todoText}
          onInput={(e) => setTodoText(e.target.value)}
        />
        <button onClick={() => addTodo()}>Add</button>
      </div>
      <div>
        <ul>
          {todoData.map((todo) => (
            <li key={todo.id}>
              <input
                type="checkbox"
                checked={todo.checked}
                onClick={() => toggleTodo(todo.id)}
              />
              <span
                style={{ textDecoration: todo.completed ? 'line-through' : '' }}
              >
                {todo.content}
              </span>
              <button onClick={() => removeTodo(todo.id)}>Delete</button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
